<template>
  <div class="stage-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <!-- <el-breadcrumb-item>
          <a @click="goToCourse">课程</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <a @click="goToCourseDetail">{{ courseName || '课程详情' }}</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span>阶段信息</span>
        </el-breadcrumb-item> -->
      </el-breadcrumb>
    </div>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="阶段名称" prop="stageName">
        <el-input
          v-model="queryParams.stageName"
          placeholder="请输入阶段名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="课程顺序" prop="stageOrder">
        <el-input
          v-model="queryParams.stageOrder"
          placeholder="请输入课程顺序"
          clearable
          @keyup.enter="handleQuery"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 130px">
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:stage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:stage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:stage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:stage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stageList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="阶段ID" align="center" prop="id" />
      <el-table-column label="阶段名称" align="center" prop="stageName" />
      <!-- <el-table-column label="所属课程ID" align="center" prop="courseId" /> -->
      <el-table-column label="课程顺序" align="center" prop="stageOrder" sortable="custom" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:stage:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:stage:remove']">删除</el-button>
          <el-button link type="success" icon="View" @click="handleViewCases(scope.row)" v-hasPermi="['system:stage:view']">查看案例</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改阶段对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="stageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="阶段名称" prop="stageName">
          <el-input v-model="form.stageName" placeholder="请输入阶段名称" />
        </el-form-item>
        <!-- <el-form-item label="所属课程ID" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入所属课程ID，关联course表的课程ID" />
        </el-form-item> -->
        <el-form-item label="课程顺序" prop="stageOrder">
          <el-input v-model="form.stageOrder" placeholder="请输入课程顺序，表示该阶段在课程中的顺序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listStage, getStage, delStage, addStage, updateStage } from "@/api/coursemanagement/stage";
import { useRouter, useRoute } from "vue-router";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const router = useRouter();
const route = useRoute();

// 定义组件属性
const props = defineProps({
  courseId: {
    type: String,
    required: true
  },
  courseName: {
    type: String,
    default: ''
  }
});

// 从路由参数获取courseId和courseName
const courseId = ref(props.courseId || route.query.courseId);
const courseName = ref(props.courseName || route.query.courseName);

const stageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stageName: null,
    courseId: props.courseId || null,
    stageOrder: null,
    status: null,
  },
  rules: {
    courseId: [
      { required: true, message: "所属课程ID，关联course表的课程ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询阶段列表 */
function getList() {
  loading.value = true;
  queryParams.value.courseId = courseId.value;
  // 默认按课程顺序从小到大排序
  if (!queryParams.value.orderByColumn) {
    queryParams.value.orderByColumn = 'stageOrder';
    queryParams.value.isAsc = 'asc';
  }
  listStage(queryParams.value).then(response => {
    stageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 导航方法
function goToCourse() {
  router.push('/coursemanagement/course');
}

function goToCourseDetail() {
  router.push({
    path: '/coursemanagement/detail',
    query: { id: courseId.value, courseName: courseName.value }
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    stageName: null,
    courseId: props.courseId,
    stageOrder: null,
    status: "0",
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("stageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加阶段";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStage(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改阶段";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stageRef"].validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      if (form.value.id != null) {
        updateStage(form.value).then(response => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(() => { proxy.$modal.closeLoading(); });
      } else {
        addStage(form.value).then(response => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(() => { proxy.$modal.closeLoading(); });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除阶段编号为"' + _ids + '"的数据项？').then(function() {
    return delStage(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/stage/export', {
    ...queryParams.value
  }, `stage_${new Date().getTime()}.xlsx`)
}

/** 查看案例按钮操作 */
function handleViewCases(row) {
  // 跳转到案例详情页面，传递阶段ID、阶段名称、课程ID和课程名称作为参数
  router.push({
    path: "/coursemanagement/casedetail",
    query: { 
      stageId: row.id,
      stageName: row.stageName,
      courseId: courseId.value,
      courseName: courseName.value
    },
  });
}


/** 处理排序变化 */
function handleSortChange(column) {
  if (column.prop === 'stageOrder') {
    queryParams.value.orderByColumn = 'stageOrder';
    queryParams.value.isAsc = column.order === 'ascending' ? 'asc' : 'desc';
  } else {
    // 默认按课程顺序从小到大排序
    queryParams.value.orderByColumn = 'stageOrder';
    queryParams.value.isAsc = 'asc';
  }
  getList();
}

// 监听 courseId 的变化，当变化时执行 getList()
watch(() => props.courseId, () => {
  queryParams.value.courseId = props.courseId;
  getList();
});
onMounted(() => {
  getList();
});
</script>

<style scoped>
.stage-container {
  padding: 20px;
}

.breadcrumb-container {
  margin-bottom: 20px;
}

.breadcrumb-container a {
  color: #409EFF;
  cursor: pointer;
  text-decoration: none;
}

.breadcrumb-container a:hover {
  color: #66b1ff;
}
</style>